package com.starhub.domain.ai.controller;

import com.starhub.monitor.dto.AIChatLogDto;
import com.starhub.monitor.service.IAIChatLogService;
import com.starhub.utils.Util;
import com.starhub.application.agent.dto.AIChatInfo;
import com.starhub.application.agent.result.AIAgentResult;
import com.starhub.application.agent.result.AiChatResult;
import com.starhub.application.agent.service.IChatService;
import com.starhub.common.bean.ResultResp;
import com.starhub.common.security.util.SecurityUtils;

import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 聊天控制器
 * 提供基本的聊天功能接口
 */
@RestController
@RequestMapping("/api/starhub/chat")
public class ChatController {

    private static final Logger log = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    private IChatService chatService;

    @Autowired
    private IAIChatLogService aiChatLogService;

    /**
     * 智能体初始化
     * @param agentId 智能体id
     * @return 模型响应
     */
    @GetMapping("/initAgent")
    public ResultResp<AIAgentResult> initAgent(@RequestParam(value = "agentId") String agentId) {
        try {
            return ResultResp.success(chatService.initAgentById(Long.parseLong(agentId)));
        } catch (Exception e) {
            log.error("chat error", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 普通聊天接口
     * @param identifier 智能体标识
     * @return 模型响应
     */
    @GetMapping("/initAgentByMark")
    public ResultResp<AIAgentResult> initAgentByMark(@RequestParam(value = "mark") String identifier) {
        try {
            return ResultResp.success(chatService.initAgentByMark(identifier));
        } catch (Exception e) {
            log.error("chat error", e);
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 普通聊天接口
     * @param aIChatInfo 用户消息
     * @return 模型响应
     */
    @PostMapping("/call")
    public ResultResp<AiChatResult> chat(@RequestBody AIChatInfo aIChatInfo) {
        try {
            aIChatInfo.setUserId(SecurityUtils.getCurrentUserId());
            aIChatInfo.setRequestTime(LocalDateTime.now());
            return ResultResp.success(chatService.chat(aIChatInfo));
        } catch (Exception e) {
            log.error("chat error", e);
            // 记录失败日志
            aiChatLogService.logFailure(AIChatLogDto.builder()
                .agentId(aIChatInfo.getAgentId())
                .userId(Util.getLongValue(aIChatInfo.getUserId()))
                .sessionId(aIChatInfo.getSessionId())
                .requestContent(aIChatInfo.getUserMessage())
                .requestTime(aIChatInfo.getRequestTime())
                .responseTime(LocalDateTime.now())
                .errorMessage(e.getMessage())
                .build()
            );
            return ResultResp.fail(e.getMessage(),e);
        }
    }

    /**
     * 普通聊天接口
     * @param chatInfo 用户消息
     * @return 模型响应
     */
    @PostMapping("/callStream")
    public void chatStream(@RequestBody AIChatInfo chatInfo, HttpServletResponse response) throws Exception {
        chatInfo.setUserId(SecurityUtils.getCurrentUserId());
        chatInfo.setRequestTime(LocalDateTime.now());

        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");
        chatService.chatStream(chatInfo, response.getWriter());
    }
}